package cn.fan.shirotoken.service.impl;


import cn.fan.shirotoken.domian.SysToken;
import cn.fan.shirotoken.domian.User;
import cn.fan.shirotoken.mapper.SysTokenMapper;
import cn.fan.shirotoken.mapper.UserMapper;
import cn.fan.shirotoken.service.ShiroService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HTHLKJ
 */
@Service
public class ShiroServiceImpl implements ShiroService {


    @Autowired
    private UserMapper userMPMapper;
    @Autowired
    private SysTokenMapper sysTokenMPMapper;

    /**
     * 根据username查找用户
     *
     * @param username
     * @return User
     */
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(User::getUsername, username);
        User user = userMPMapper.selectOne(qw);
        return user;
    }

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    /**
     * 生成一个token
     *@param  [userId]
     *@return Result
     */
    public Map<String, Object> createToken(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        //生成一个token
//        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        String token = Jwts.builder().claim("userId", userId).setExpiration(expireTime).compact();
        //判断是否生成过token
        QueryWrapper<SysToken> wq = new QueryWrapper<>();
        wq.lambda().eq(SysToken::getUserId, userId);

        SysToken tokenEntity = sysTokenMPMapper.selectOne(wq);
        ;
        if (tokenEntity == null) {
            tokenEntity = new SysToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //保存token
            sysTokenMPMapper.insert(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
            sysTokenMPMapper.update(tokenEntity, null);
        }
        result.put("token", token);
        result.put("expire", EXPIRE);
        return result;
    }

    /**
     * 更新数据库的token，使前端拥有的token失效
     * 防止黑客利用token搞事情
     *
     * @param token
     */
    @Override
    public void logout(String token) {
//        SysTokenMP byToken = findByToken(token);
//        //生成一个token
//        token = TokenGenerator.generateValue();
//        //修改token
//        byToken.setToken(token);
//        //使前端获取到的token失效
//        sysTokenRepository.save(byToken);
        QueryWrapper<SysToken> sw = new QueryWrapper<>();
        sw.lambda().eq(SysToken::getToken, token);
        sysTokenMPMapper.delete(sw);
    }

    @Override
    public SysToken findByToken(String accessToken) {
        QueryWrapper<SysToken> wq = new QueryWrapper<>();
        wq.lambda().eq(SysToken::getToken, accessToken);
        return sysTokenMPMapper.selectOne(wq);

    }

    @Override
    public User findByUserId(Integer userId) {
//        QueryWrapper<User> wq = new QueryWrapper<>();
//        wq.lambda().eq(User::getUserId, userId);
//        return userMPMapper.selectOne(wq);
        return userMPMapper.findById(userId);
    }
}
